package yxy.game.pm2.proto;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Set;

import com.alibaba.fastjson.JSONArray;

import yxy.apple.util.FileUtility;
import yxy.apple.util.ReflectionUtility;
import yxy.cherry.game.base.message.annotation.MessageType;

public class CommandGeneratorJava extends CommandGenerator {

	private String className = "Noname";
	private String packageName = null;

	public CommandGeneratorJava(boolean trusted, String packageName, String className) {
		super(trusted);
		this.packageName = packageName;
		this.className = className;
	}

	@Override
	@Deprecated
	public void generate(JSONArray json, File output, String encoding) throws IOException {
		super.generate(json, output, encoding);
	}

	public void generate(JSONArray json, String src, String encoding) throws IOException {
		String filename = this.className + ".java";
		String path = src + "/" + this.packageName.replaceAll("\\.", "/");
		File output = new File(path + "/" + filename);
		this.generate(json, output, encoding);
	}

	@Override
	protected String assembleField(int level, String parent, String type, String name, String comment, String value, String desc, String messagefile) {
//		try {
//			if (messagefile != null) {
//				this.messagefile = messagefile;
//			}
//			if (desc != null) {
//				this.messagedesc = desc;
//			}
//			if (value.endsWith("A") && name.startsWith("Union") && name.endsWith("Rank")) {
//			if (value.endsWith("A") && name.equals("PlainsArenaFormatUI")) {
//			if (value.endsWith("A") && name.startsWith("Guard")) {
//			if (value.endsWith("A")) {
//			if (value.endsWith("A") && (name.startsWith("Seven") || name.startsWith("Temple") || name.startsWith("Senior"))) {
//				createCMDFile(name, comment, desc, messagefile);
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		String indentation = this.indent(level);
		StringBuffer buffer = new StringBuffer();
		if (comment != null) {
			buffer.append(String.format("%s//%s\r\n", indentation, comment));
		}
		if (parent != null && parent.equals("enum")) {
			buffer.append(String.format("%s%s = %s,\r\n", indentation, name, value));
		} else {
			String format = "%spublic static final %s %s = %s;\r\n";

			if (type.endsWith("String")) {
				format = "%spublic static final %s %s = \"%s\";\r\n";
			}
			buffer.append(String.format(format, indentation, type, name, value));
		}
		return buffer.toString();
	}

	@Override
	protected String assembleHeader(int level, String type, String name, String comment) {
		String indentation = this.indent(level);
		StringBuffer buffer = new StringBuffer();

		if (comment != null) {
			buffer.append(String.format("\r\n%s//%s\r\n", indentation, comment));
		}
		if (level == 0 && type == null) {
			buffer.append(String.format("package %s;\r\n", packageName));
			buffer.append("\r\n");
			buffer.append("import com.google.protobuf.MessageLite;\r\n");
			buffer.append("import yxy.cherry.game.base.message.annotation.MessageSource;\r\n");
			buffer.append("\r\n");
			buffer.append(String.format("public abstract class %s<M extends MessageLite> implements Cloneable {\r\n", className));
		} else if (type != null && type.equals("class")) {
			buffer.append(String.format("%spublic static final class %s {\r\n", indentation, name));
		} else if (type != null && type.equals("enum")) {
			buffer.append(String.format("%spublic static enum %s {\r\n", indentation, name));
		} else {
			buffer.append(String.format("%s{\r\n", indentation));
		}
		return buffer.toString();
	}

	@Override
	protected String assembleFooter(int level, String type, String name, String comment) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("\r\n" + "	abstract public void execute(MessageSource messageSource, M request) throws Exception;\r\n" + "\r\n"
				+ "	@SuppressWarnings(\"rawtypes\")\r\n" + "	public Command clone() {\r\n" + "		try {\r\n"
				+ "			return (Command) super.clone();\r\n" + "		} catch (CloneNotSupportedException e) {\r\n"
				+ "			e.printStackTrace();\r\n" + "			return null;\r\n" + "		}\r\n" + "	}");

		String indentation = this.indent(level);
		buffer.append(String.format("%s}\r\n", indentation));
		return buffer.toString();
	}

	private void createCMDFile(String name, String comment, String desc, String message) throws IOException {
		String filename = "CMD_" + name + ".java";
		String path = "./src/main/java/" + "/" + this.packageName.replaceAll("\\.", "/");
		File output = new File(path + "/" + filename);
		FileUtility.create(output);
		System.err.println("create::" + output.getPath());
		String content = assembleCMD(name, comment, desc, message);
		FileOutputStream fos = new FileOutputStream(output);
		fos.write(content.getBytes("UTF-8"));
		fos.flush();
		fos.close();
	}

	private String messagefile = null;
	private String messagedesc = null;

	private String assembleCMD(String name, String comment, String desc, String message) {
		StringBuffer buffer = new StringBuffer();

		if (message != null) {
			this.messagefile = message;
		}
		if (desc != null) {
			this.messagedesc = desc;
		}

		String formatA = //
				"package yxy.game.pm2.command;\r\n" + //
						"\r\n" + //
						"import yxy.cherry.game.base.message.MessageEmitterHandler;\r\n" + //
						"import yxy.cherry.game.base.message.annotation.MessageSource;\r\n" + //
						"import yxy.cherry.game.base.message.annotation.MessageType;\r\n" + //
						"import yxy.game.pm2.command.Command;\r\n" + //
						"import yxy.game.pm2.message.%s;\r\n" + //
						"import yxy.game.pm2.Result;\r\n" + //
						"\r\n" + //
						"/** %s %s */\r\n" + //
						"@MessageType(proto = Command.%s, classtype = %s.%sRequest.class)\r\n" + //
						"public class CMD_%s extends Command<%s.%sRequest> {\r\n" + //
						"\r\n" + //
						"	@Override\r\n" + //
						"	public void execute(MessageSource messageSource, %s.%sRequest request) {\r\n" + //
						"		String playerCode = messageSource.getTag();\r\n" + //
						"		// TODO 处理请求参数\r\n" + //
						"\r\n" + //
						"		%s.%sResponse.Builder response = %s.%sResponse.newBuilder();\r\n" + //
						"\r\n" + //
						"		// TODO 处理响应封装\r\n" + //
						"\r\n" + //
						"		send(messageSource, response, Result.Success);\r\n" + //
						"	}\r\n" + //
						"\r\n" + //
						"	private void send(MessageSource messageSource, %s.%sResponse.Builder response, Result result) {\r\n" + //
						"		response.setResult(result.packResult());\r\n" + //
						"		MessageEmitterHandler.getInstance().send(messageSource, response.build());\r\n" + //
						"	}\r\n" + //
						"}";//
		buffer.append(String.format(formatA, messagefile, messagedesc, comment, name, messagefile, name, name, messagefile, name, messagefile, name,
				messagefile, name, messagefile, name, messagefile, name));

		return buffer.toString();
	}
}
